package com.zz.config;

import com.zz.entity.Caseresult;
import com.zz.service.ICaseresultService;
import com.zz.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.testng.IResultMap;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class TestNGResultListener extends TestListenerAdapter {

    //暂时埋下问题
    private  static ICaseresultService caseresultService;

    /*
        通过set注入才可以使用
     */
    @Autowired
    public void setCaseresultService(ICaseresultService caseresultService){
        TestNGResultListener.caseresultService = caseresultService;
    }

    private List<Caseresult> caseresults = new ArrayList<>();

    @Override
    public void onStart(ITestContext testContext) {
      log.info("测试用例开始执行...");
    }

    @Override
    public void onFinish(ITestContext testContext) {
        log.info("测试用例执行完毕,开始处理执行结果...");
        //生成批次id
        IdWorker idWorker = new IdWorker();
        long batchId = idWorker.nextId();
        //通过的测试用例
        IResultMap passedTests = testContext.getPassedTests();
        addTestResult(passedTests, batchId);
        //失败的测试用例
        IResultMap failedTests = testContext.getFailedTests();
        addTestResult(failedTests, batchId);
        //忽略的测试用例
        IResultMap skippedTests = testContext.getSkippedTests();
        addTestResult(skippedTests, batchId);
        //保存
        caseresultService.saveBatch(caseresults);
    }

    // 毫秒值+随机数 long l = System.currentTimeMillis(); //毫秒值
    private void addTestResult(IResultMap iResultMap, long batchId) {
        Set<ITestResult> allResults = iResultMap.getAllResults();
        for (ITestResult result : allResults) {
            log.info("结果数据: {}", result);
            Caseresult caseresult = new Caseresult();
            caseresult.setBatchId(batchId+""); //批次id
            caseresult.setMethodName(result.getMethod().getMethodName());
            caseresult.setBeginTime(new Date(result.getStartMillis()));
            caseresult.setEndTime(new Date(result.getEndMillis()));
            //三元运算符
            caseresult.setErrorMsg(result.getThrowable()!=null?result.getThrowable().getMessage():"");
            caseresult.setUseTime(Integer.valueOf(String.valueOf(result.getEndMillis()-result.getStartMillis())));
            caseresult.setStatus(result.getStatus()==1?"success":"fail");
            caseresults.add(caseresult);
        }
    }
}
